import calendar
import datetime

from flask import Blueprint, current_app
from flask_cors import cross_origin
from flask import request
from app.Services.FinanceServices.ExpenseServices import ExpenseServices
from app.Utils.Utils import success_response, error_response

# 1. 创建蓝图对象
expense_bp = Blueprint(
    name='expense_bp',
    import_name=__name__,
    url_prefix='/exp'
)

exp_services = ExpenseServices()


@expense_bp.route('/add', methods=['POST'])
def add():
    """
    新增支出数据
    :return:
    """
    user_id = request.json['user_id']
    first_cate_id = request.json['first_cate_id']
    second_cate_id = request.json['second_cate_id']
    amount = request.json['amount']
    date = request.json['date']
    note = request.json.get('note', None)
    attach_path = request.json.get('attach_path', None)
    print(user_id, first_cate_id, second_cate_id, amount, date, note, attach_path)
    status, response = exp_services.add_expense(user_id, first_cate_id, second_cate_id, amount, date, note, attach_path)
    if status:
        print(response)
        return success_response(data=response)
    else:
        print(response)
        return success_response(message=response)


@expense_bp.route('/list', methods=['GET'])
def get_list():
    """
    支出数据列表
    :return:
    """
    pass


@expense_bp.route('/statistics', methods=['POST'])
def get_card():
    """
    支出卡片累计数据
    :return:
    """
    year = request.json.get('year', None).split('-')[0]
    month = request.json.get('month', None).split('-')[1]
    user_id = request.json['user_id']
    status, res = exp_services.get_expense_summary(user_id, year, month)
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


@expense_bp.route('/exp_struct', methods=['POST'])
def get_exp_struct():
    """
    支出结构数据
    :return:
    """
    user_id = request.json['user_id']
    first_cate_id = request.json.get('first_cate_id', None)
    second_cate_id = request.json.get('second_cate_id', None)
    # 统计所在月的支出结构
    year = request.json.get('start_date', None).split('-')[0]
    month = request.json.get('start_date', None).split('-')[1]
    _, last_day = calendar.monthrange(int(year), int(month))
    start_date = datetime.date(int(year), int(month), 1)
    end_date = datetime.date(int(year), int(month), last_day)
    status, res = exp_services.get_expense_detail(user_id, first_cate_id, second_cate_id, start_date, end_date)
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


# 获取特定日期的支出数据
@expense_bp.route('/date_exp', methods=['POST'])
def get_date_exp():
    """
    获取特定日期的支出数据
    :return:
    """
    user_id = request.json['user_id']
    date = request.json['date']
    # 转换成date格式
    date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
    status, res = exp_services.get_daily_expense_detail(user_id, date)
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


# 获取所有的支出一级分类
@expense_bp.route('/first_cate', methods=['GET'])
def get_first_cate():
    """
    获取所有的支出一级分类
    :return:
    """
    status, res = exp_services.get_first_cate()
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


# 根据一级分类id获取二级分类
@expense_bp.route('/get_second_cate_by_first_cate_id', methods=['POST'])
def get_second_cate():
    """
    根据一级分类id获取二级分类
    :return:
    """
    print(request.json)
    first_cate_id = request.json['first_cate_id']
    status, res = exp_services.get_second_cate_by_first_cate_id(first_cate_id)
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


# 获取某个月的支出数据
@expense_bp.route('/month_exp', methods=['POST'])
def get_month_exp():
    """
    获取某个月的支出数据
    :return:
    """
    user_id = request.json['user_id']
    year = int(request.json['date'].split('-')[0])
    month = int(request.json['date'].split('-')[1])
    status, res = exp_services.get_month_expense_detail(user_id, year, month)
    if status:
        return success_response(data=res)
    else:
        return success_response(code=400, message=res)


# 根据id更新支出明细
@expense_bp.route('/edit_exp', methods=['POST'])
def edit_exp():
    """
    根据支出ID更新支出单条记录。
    """
    exp_form = request.json
    exp_id = exp_form.pop('id')
    exp_form.pop('first_cate_name')
    exp_form.pop('second_cate_name')
    status, res = exp_services.update_expense(exp_id, **exp_form)
    if status:
        current_app.logger.info(f"更新支出成功，参数：{exp_form}")
        return success_response(data=res)
    else:
        current_app.logger.warning(f"更新支出失败，参数：{exp_form}")
        current_app.logger.error(f"更新支出失败，原因：{res}")
        return error_response(message=res)


# 根据id删除支出明细
@expense_bp.route('/delete_exp', methods=['POST'])
def delete_exp():
    """
    根据ID删除支出记录。
    """
    exp_id = request.json['exp_id']
    status, res = exp_services.delete_expense(exp_id, user_id=1)
    if status:
        current_app.logger.info(f"根据ID删除支出记录成功，参数：{exp_id}")
        return success_response(data=res)
    else:
        current_app.logger.error(f"根据ID删除支出记录失败，参数：{exp_id}")
        return error_response(message=res)

